import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, TextInput, ScrollView,
	PixelRatio, Keyboard, ActivityIndicator
} from 'react-native';
import { API, API_GENERATE } from '../../../config/api';
import StorageHelper from '../../../utils/storageHelper';
import ToastUtil from '../../../utils/toast';
import HTTP from '../../../utils/http';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { Common } from '../../../component/common/Common.js'
import { cStyles } from '../RequirementStyle.js';
import { OptionCheck } from '../../enterprise/_components/Component.js';
import ModalDoubleComponent from '../../../component/ModalDoubleComponent.js';
import { RequirementTitle, InputRow, RowBtn, LargeBtn } from '../component/Component.js';
const scale = GLOBAL.SCALE;
const optionCheck = {
	modalVisible: false,
	checkObj: {},
	onBgPress: () => { },
	onPress: () => { },
	data: []
}
const curCheckObj = {
	goodsId: '',
	serialNumber: '',
}
let demandTypeList = [];
let deliveryMethodList = [];
let serialNumberList = [];
const arrowPic = require('../../../imgs/arrow-left.png');
let sendData = {
	demandType: 'ADD',//需求类型
	// deliveryMethod: 'S',//交货方式
}

let curUserOptionType = 'contact';
let curLongOrderIndex = 0;
let curEnterPrise = null;
let listNull;
let ifNull;
let addOnly = false;

export class RequirementAdd extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		// const { logistical, user, enterprise, setLogistical,setUserName,setEnterprise} = params;
		const { setLogistical, setUserName, setEnterprise, ifNullParams } = params;
		let { logistical, user, enterprise, } = params;
		if (logistical) {
			ifNull = ifNullParams;
			setLogistical(logistical);
		}
		if (enterprise) {
			setEnterprise(enterprise);
			androidBranch = true;
		}
		if (user) {
			if (curUserOptionType == 'contact') {
				sendData.linkBy = user.userId;//userId
			} else {
				sendData.staffId = user.userId;//userId
			}
			setUserName(curUserOptionType, user.userName);
		} else {
		}

		return {
			headerTitle: '客户需求',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		};
	};

	constructor(props) {
		super(props);

		curLongOrderIndex = 0;
		curEnterPrise = null;

		this.state = {
			goodsModal: false,// 商品数据
			goodsValue: '请选择',
			goodsListVal: [],
			goodsList: [],

			logisticalList: [],
			demandType: 'ADD',//需求类型
			deliveryMethod: 'S',//交货方式
			serialNumber: false,
			serialNumberText: '请选择',
			goodsNameLong: '请选择',
			goodsNameAdd: '请选择',
			companyName: '请选择',
			loaded: true,
			company: {},
			quantity: '',
			resultModalVisible: false,
			contact: '请选择',
			reference: '请选择',
			keyboard: false,
			remark: false,
			modalVisible: false,
		}
		this._didPressDemandTypeBtn = this._didPressDemandTypeBtn.bind(this);
		this._didPressDeliveryMethodBtn = this._didPressDeliveryMethodBtn.bind(this);
		this._getLogisticalViews = this._getLogisticalViews.bind(this);
		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);
		//this._fetchLongOrder = this._fetchLongOrder.bind(this);
		this._setUserName = this._setUserName.bind(this);
		this._setEnterprise = this._setEnterprise.bind(this);
		this._setLogistical = this._setLogistical.bind(this);
		this._setLongOrder = this._setLongOrder.bind(this);
	}

	_setUserName (type, userName) {
		console.log(type, userName);
		if (type == 'contact') {
			this.setState({
				contact: userName
			});
		} else {
			this.setState({
				reference: userName
			});
		}
	}

	_setEnterprise (company) {
		console.log(company);
		if (company) {
			curEnterPrise = company;
			this.setState({
				company,
				linkBy: company.linkBy,
				linkPhone: company.linkPhone,
				contactTxt2: company.linkBy,
				// reference:company.linkBy
				companyName: company.companyName,
			});
			sendData.companyName = company.companyName;
			sendData.companyId = company.companyId;
			// sendData.goodsName = company.goodsName;
			// sendData.goodsId = company.objectId;
			sendData.quantity = company.quantity || sendData.quantity;
			sendData.uom = company.uom;
			sendData.linkBy = company.linkBy;
			sendData.linkPhone = company.linkPhone;
		}

	}

	_setLogistical (logistical) {
		const { index } = logistical;
		const { logisticalList } = this.state;
		if (index) {
			if (listNull && ifNull) {
				this.setState({
					logisticalList: []
				});
				return;
			} else {
				logisticalList[index - 1] = logistical;
			}
		} else {
			logisticalList.push(logistical);
		}
		this.setState({
			logisticalList
		});
	}

	_gotoList = () => {
		let { company } = this.state;
		this.props.navigation.navigate('RequirementListPage', {
			//pushIndex: this.data.pushIndex,
			//orderType: this.data.params.orderType,
			//periodType: this.data.params.periodType,
			goCallBack: (data, index) => {
				console.log('longdata', data);
				if (data) {
					//alert(1);
					data.longOrderId = data.orderId;
					data.orderId = '';
					company.uom = data.companyName;
					company.quantity = data.orderItemList[0] ? data.orderItemList[0].quantity : '';
					sendData.quantity = data.orderItemList[0] ? data.orderItemList[0].quantity : '';
					sendData.goodsName = data.orderItemList[0] ? data.orderItemList[0].goodsName : '';
					sendData.goodsName = data.orderItemList[0] ? data.orderItemList[0].goodsName : '';
					sendData.uom = data.companyName;
					sendData.companyName = data.companyName;
					sendData.staffId = data.bizStaffId;
					sendData.goodsId = data.orderItemList[0] ? data.orderItemList[0].goodsId : '';
					sendData.companyId = data.companyId;
					this.setState({
						data: data,
						onShow: true,
						companyName: data.companyName,
						goodsNameLong: data.orderItemList[0] ? data.orderItemList[0].goodsName : '',
						serialNumberText: data.organId,
						company: company,
						reference: data.bizStaffName,
					})
					console.log('call', data)
					//this.data.pushIndex = index;
				}
			}
		});
	}

	async componentWillMount () {
		//this._getGoodsList();//商品列表
		sendData = {
			demandType: 'ADD',//需求类型
			// deliveryMethod: 'S',//交货方式
		}
		//await this._fetchLongOrder();//查询长协编号
		this.props.navigation.setParams({
			setUserName: this._setUserName,
			setEnterprise: this._setEnterprise,
			setLogistical: this._setLogistical,
		});
		optionCheck.onBgPress = () => {
			optionCheck.modalVisible = false;
			this.setState({
				serialNumber: !this.state.serialNumber,
			});
		};

		const dataDictionaryStr = await StorageHelper.get(STORAGE_CONSTANT.DICTIONARY);
		const dataDictionary = dataDictionaryStr ? JSON.parse(dataDictionaryStr) : {};


		if (dataDictionary && dataDictionary['DEMAND_TYPE']) {
			demandTypeList = dataDictionary['DEMAND_TYPE'];
		} else {
			const demandTypes = await HTTP.POST(API_GENERATE(API.GET_DATA_DICTIONARY), { dictTypeCode: "DEMAND_TYPE" });
			demandTypeList = demandTypes.map((item) => {
				const { dictKey, dictName } = item;
				return {
					key: dictKey,
					val: dictName,
				}
			});
			dataDictionary['DEMAND_TYPE'] = demandTypeList;
			StorageHelper.set(STORAGE_CONSTANT.DICTIONARY, dataDictionary);
		}
		if (addOnly) {
			demandTypeList = demandTypeList.filter((item) => {
				const { key } = item;
				return key != 'LONG';
			});
		}
		console.log(addOnly, demandTypeList)

		if (dataDictionary && dataDictionary['EC_DELIVERY_TYPE ']) {
			deliveryMethodList = dataDictionary['EC_DELIVERY_TYPE '];
		} else {
			const demandTypes = await HTTP.POST(API_GENERATE(API.GET_DATA_DICTIONARY), { dictTypeCode: "EC_DELIVERY_TYPE" });
			deliveryMethodList = demandTypes.map((item) => {
				const { dictKey, dictName } = item;
				return {
					key: dictKey,
					val: dictName,
				}
			});
			dataDictionary['EC_DELIVERY_TYPE'] = deliveryMethodList;
			StorageHelper.set(STORAGE_CONSTANT.DICTIONARY, dataDictionary);
		}

		this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
		this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));

		let account = {};
		try {
			let accountStr = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
			if (accountStr) {
				account = JSON.parse(accountStr);
			}
		} catch (error) {
			console.log(error);
		}

		/*const responseData = await HTTP.POST(API_GENERATE(API.GET_COMPANY_GOODS), {
			pageNo: 1,
			pageSize: 10,
			corpType: '2',
		});
		if (responseData.rows && responseData.rows.length) {
			curEnterPrise = responseData.rows[0];
		}
		this._setEnterprise(curEnterPrise)
		*/
		const { userId, userName } = account;
		this.setState({
			loaded: false,
			reference: userName,
		});
		sendData.staffId = userId;
	}

	componentWillUnmount () {
		this.state = {};
	}

	//获取商品 - 数据APPRO_PRICE_BATCH1/GET_GOODSLIST
	async _getGoodsList () {
		let responseData = await HTTP.POST(API_GENERATE(API.GET_GOODSLIST), { companyId: sendData.companyId });
		if (responseData) {
			responseData.map((item, index) => {
				item.text = item.goodsName;
				item.val = item.goodsId;
				if (item.children.length > 0) {
					item.dataSource = item.children;
					item.dataSource.map((items, index) => {
						items.text = items.goodsName;
						items.val = items.goodsId;
						return items
					})
				}
				return item;
			});
			console.log('responseData', responseData);
			this.setState({
				goodsList: responseData
			})
		}
	}

	/* ---选择产品--- */
	_selecGoods = (obj, index) => {
		if (!sendData.companyId) {
			ToastUtil.showWarning('请先选择客户');
			return false;
		}
		this._getGoodsList();

		var onTe = true;
		for (key in obj) {
			obj[key] = true;
			if (key == 'settlementPriceModal' || key == 'reasectPriceModal') {
				if (!sendData.goodsId) {
					onTe = false;
					ToastUtil.showWarning('请先选择商品');
				}
			}
		}
		if (onTe) {
			this.setState(obj);
		}

	}
	//选商品  关闭按钮
	_cancelPress = () => {
		this.setState({ goodsModal: false })
	}
	//选商品  确定按钮
	_confirmPress = (data) => {
		if (data.length > 0) {
			this.setState({
				goodsModal: false,
				goodsValue: data[0].goodsName,
			}, function () {
				this.setState({
					goodsNameAdd: data[0].goodsName
				})
				sendData.goodsId = data[0].goodsId;
				sendData.goodsName = data[0].goodsName;
			})
		} else {
			this.setState({
				goodsModal: false,
			})
		}
	}

	componentWillUnmount () {
		this.state = {};
		try {
			this.keyboardDidShowListener.remove();
			this.keyboardDidHideListener.remove();
		} catch (error) {
			console.log(error);
		}
	}


	_keyboardDidShow () {
		this.setState({
			keyboard: true,
		});
	}

	_keyboardDidHide () {
		this.setState({
			keyboard: false,
		});
	}

	_setLongOrder (index) {
		const { val, key, data } = serialNumberList[index];
		optionCheck.modalVisible = false;
		optionCheck.checkObj = { dictKey: key };
		this.setState({
			serialNumber: !this.state.serialNumber,
			serialNumberText: val,
			company: data,
			deliveryMethod: data.deliveryMethod,//data.deliveryType
			goodsNameLong: data.goodsName,
			contactTxt1: data.linkBy,
		});
		sendData.companyType = 1;
		sendData.companyName = data.companyName;
		sendData.companyId = data.companyId;
		sendData.goodsId = data.goodsId;
		sendData.goodsName = data.goodsName;
		sendData.quantity = data.quantity;
		sendData.uom = data.uom;
		sendData.linkBy = data.linkBy;
		sendData.linkPhone = data.linkPhone;
		curCheckObj.serialNumber = val;
	}

	async _fetchLongOrder () {
		const responseData = await HTTP.POST(API_GENERATE(API.ORDER_LONG_LIST), {
			orderType: 'S',   //订单类型 s-销售 p-采购
			periodType: 'L',  //合同类型 s-普通 l-长约 
		});
		//alert(responseData.rows);
		if (responseData.rows) {
			serialNumberList = responseData.rows.map((item, i) => {
				const { orderId } = item;
				return {
					key: orderId,
					val: orderId,
					data: item,
				}
			});
			optionCheck.data = serialNumberList.map((item, i) => {
				const { key, val } = item;
				return { text: val, val: key, index: i }
			});
			if (serialNumberList.length) {
				this._setLongOrder(curLongOrderIndex);
			} else {
				addOnly = true;
				//没有长些编号
				this.setState({
					demandType: 'ADD',
				});
				if (!curEnterPrise) {
					const responseData = await HTTP.POST(API_GENERATE(API.GET_COMPANY_GOODS), {
						pageNo: 1,
						pageSize: 10,
						corpType: '2',
					});
					if (responseData.rows && responseData.rows.length) {
						curEnterPrise = responseData.rows[0];
					}
				}
				this._setEnterprise(curEnterPrise)
			}
		}

	}

	async _didPressDemandTypeBtn (demandType) {
		sendData = {
			demandType: demandType,//需求类型
		}
		this.setState({
			demandType,
			company: {},
			companyName: '',
			logisticalList: [],
			deliveryMethod: 'S',//交货方式
			goodsNameLong: '请选择',

		});
		if (demandType == 'LONG') {
			//this._setLongOrder(curLongOrderIndex);
		} else {
			/*if (!curEnterPrise) {
				const responseData = await HTTP.POST(API_GENERATE(API.GET_COMPANY_GOODS), {
					pageNo: 1,
					pageSize: 10,
					corpType: '2',
				});
				if (responseData.rows && responseData.rows.length) {
					curEnterPrise = responseData.rows[0];
				}
			}
			this._setEnterprise(curEnterPrise)*/
		}
	}

	_didPressDeliveryMethodBtn (deliveryMethod) {
		this.setState({
			deliveryMethod
		});
	}

	render () {
		//for 需求类型
		const { pageStatus, demandType, deliveryMethod, remark, keyboard, loaded, goodsList, goodsListVal, goodsModal } = this.state;
		const loadedCell = loaded ? <View style={styles.loadedCell}><ActivityIndicator
			animating={true}
			color={'#fff'}
			size="small"
		/></View> : null;

		let containerStyle = null;
		if (remark) {
			containerStyle = { top: -280 * scale, }
		} else if (keyboard) {
			containerStyle = { top: -180 * scale, }
		}

		const demandTypeBtns = demandTypeList.map((item, i) => {
			const { key, val } = item;
			const isCurrent = (demandType == key);
			return (
				<RowBtn onPress={this._didPressDemandTypeBtn} text={val} isCurrent={isCurrent} key={key} id={key} />
			);
		});
		const deliveryMethodTypeBtns = deliveryMethodList.map((item, i) => {
			const { key, val } = item;
			const isCurrent = (deliveryMethod == key);
			return (
				<RowBtn onPress={this._didPressDeliveryMethodBtn} text={val} isCurrent={isCurrent} key={key} id={key} style={{ marginTop: 6 * scale }} />
			);
		});
		const logisticalViews = this._getLogisticalViews();
		const demandTypeViews = this.getDemandTypeViews();

		return (
			<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>
				<View style={[styles.container, containerStyle]}>
					<RequirementTitle text={'基础信息'} />
					<View style={styles.wrap}>

						<InputRow text={'需求类型'}>
							<View style={styles.inputRowRight}>
								{demandTypeBtns}
							</View>
						</InputRow>
						{demandTypeViews}
						<InputRow text={'交货方式'}><View style={[styles.inputRowRight, { height: 76 * scale, paddingTop: 6 * scale }]}>
							{deliveryMethodTypeBtns}
						</View></InputRow>

						<View style={styles.remarkCell}>
							<Text style={cStyles.text}>备注</Text>
							<TextInput
								ref="remarkTextInput"
								style={styles.remarkTextInput}
								underlineColorAndroid='transparent'
								placeholderTextColor="#999"
								maxLength={500}
								editable={true}
								multiline={true}
								onChangeText={(txt) => { sendData.remark = txt; }}
								onFocus={() => {
									this.setState({
										remark: true,
									})
								}}
								onBlur={() => {
									this.setState({
										remark: false,
									})
								}}
							/>
						</View>

					</View>
					<RequirementTitle text={'物流信息'} />
					<View style={styles.wrap}>
						{logisticalViews}
					</View>
					<View style={styles.wuliuBtnCell}>
						<TouchableOpacity activeOpacity={0.5} style={styles.wuliuBtn} onPress={() => {
							const { navigate } = this.props.navigation;
							navigate('LogisticalPage', {
							});
						}}>
							<Text style={styles.wuliuBtnText}>添加物流</Text>
						</TouchableOpacity>
					</View>
					{this.state.modalVisible ? <LargeBtn text={'提交'} /> : <LargeBtn onPress={this._didPressLargeBtn} text={'提交'} />}
					{/*<Modal animationType={"fade"}
						transparent={true}
						visible={this.state.modalVisible}>
						<View style={styles.modalBg}>
						</View>
					</Modal>*/}
				</View>
				{loadedCell}
				<OptionCheck {...optionCheck} />
				{goodsList.length > 0 ? (<ModalDoubleComponent
					modalVisible={goodsModal}
					dataSource={goodsList}
					title='选择商品'
					selectVals={goodsListVal}
					single={1}
					cancelPress={this._cancelPress}
					confirmPress={this._confirmPress}
				/>) : null}
			</ScrollView>
		)
	}

	_providerFn = () => {
		let { providerData, company } = this.state;
		var _this = this;
		this.props.navigation.navigate('SeachSupplierPage', {
			orderType: 'S',
			type: 'RequirementAdd',
			callback: function (selectData) {
				let { companyName, companyId, linkPhone, linkBy } = selectData;
				company.linkPhone = linkPhone;
				company.linkBy = linkBy;
				sendData.linkBy = linkBy;
				sendData.linkPhone = linkPhone;
				_this.setState({
					companyName,
					providerData,
					company,
					goodsModal: false,// 商品数据
					goodsValue: '请选择',
					goodsListVal: [],
					goodsList: [],
					goodsNameAdd: '请选择'//重新选择客户置空已选择商品
				}, function () {
					sendData.companyId = companyId;
					sendData.companyName = companyName;

					sendData.goodsId = '';
					sendData.goodsName = '';

				})
			}
		});
	}

	getDemandTypeViews () {
		const { goodsModal, demandType, serialNumberText, goodsNameLong, goodsNameAdd, companyName, company, contactTxt1, contactTxt2, reference } = this.state;
		var date = new Date;
		var month = date.getMonth() + 2;
		month = month > 12 ? 1 : month;
		if (demandType == 'LONG') {//长协
			//this._fetchLongOrder();
			let quantityStr = company.quantity ? Number(company.quantity) + '' : '';
			return (
				<View >
					<InputRow text={'长协编号'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => { this._gotoList() }}
							activeOpacity={0.5} >
							<Text style={cStyles.text}>{serialNumberText}</Text>
							<Image source={arrowPic} style={styles.arrowPic} />
						</TouchableOpacity>
					</InputRow>
					{/*<InputRow text={'客户名称'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{company.companyName}</Text>
						</View>
					</InputRow>*/}

					<InputRow text={'计划月份'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => { }} activeOpacity={0.5} >
							<Text style={cStyles.text}>{month}月</Text>
						</TouchableOpacity>
					</InputRow>
					<InputRow text={'商品名称'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{goodsNameLong && goodsNameLong == '请选择' ? '' : goodsNameLong}</Text>
						</View>
					</InputRow>

					<InputRow text={'数量'}>
						<View style={styles.inputRowRight}>
							<TextInput
								ref="quantityInput"
								style={cStyles.textInput}
								underlineColorAndroid='transparent'
								placeholder={"请输入"}
								placeholderTextColor="#999"
								maxLength={30}
								editable={true}
								defaultValue={quantityStr}
								keyboardType="numeric"
								onChangeText={(txt) => { sendData.quantity = txt; }}
							/></View>
					</InputRow>
					<InputRow text={'单位'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{company.uom}</Text>
						</View>
					</InputRow>

					<InputRow text={'联系人'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{company.linkBy}</Text>
						</View>
					</InputRow>

					<InputRow text={'联系电话'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{company.linkPhone}</Text>
						</View>
					</InputRow>

					<InputRow text={'业务员'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{reference}</Text>
						</View>
					</InputRow>
				</View>
			);
		} else {//新增
			const { linkPhone } = this.state;
			let quantityStr = company.quantity ? Number(company.quantity) + '' : '';

			return (
				<View >
					<InputRow text={'计划月份'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => { }} activeOpacity={0.5} >
							<Text style={cStyles.text}>{month}月</Text>
						</TouchableOpacity>
					</InputRow>
					<InputRow text={'客户名称'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => { this._providerFn() }} activeOpacity={0.5} >
							<Text style={cStyles.text}>{companyName}</Text>
							<Image source={arrowPic} style={styles.arrowPic} />
						</TouchableOpacity>
					</InputRow>


					{/*<InputRow text={'商品名称'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => {
							const { company, serialNumber } = this.state;
							optionCheck.checkObj = { dictKey: curCheckObj.goodsId };
							if (company && company.goodsVO) {
								const { goodsVO } = company;
								optionCheck.modalVisible = true;
								optionCheck.title = '商品';
								optionCheck.onPress = (index) => {
									const { goodsCateName, objectId } = goodsVO[index];
									console.log(goodsCateName, objectId);
									optionCheck.modalVisible = false;
									this.setState({
										goodsNameAdd: goodsCateName,
										serialNumber: !serialNumber
									});
									sendData.goodsId = objectId;
									sendData.goodsName = goodsCateName;
									curCheckObj.goodsId = objectId;
								};
								optionCheck.data = goodsVO.map((item, index) => {
									return {
										text: item.goodsCateName,
										val: item.objectId,
										index
									}
								});
							}

							this.setState({
								serialNumber: !serialNumber,
							});
						}} activeOpacity={0.5} >
							<Text style={cStyles.text}>{goodsNameAdd}</Text>
							<Image source={arrowPic} style={styles.arrowPic} />
						</TouchableOpacity>
					</InputRow>*/}
					<InputRow text={'商品名称'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]}
							onPress={() => { this._selecGoods({ goodsModal }) }} activeOpacity={0.5} >
							<Text style={cStyles.text}>{goodsNameAdd}</Text>
							<Image source={arrowPic} style={styles.arrowPic} />
						</TouchableOpacity>
					</InputRow>
					<InputRow text={'数量'}>
						<View style={styles.inputRowRight}>
							<TextInput
								ref="quantityInput"
								style={cStyles.textInput}
								underlineColorAndroid='transparent'
								placeholder={"请输入"}
								placeholderTextColor="#999"
								maxLength={30}
								editable={true}
								keyboardType="numeric"
								defaultValue={quantityStr}
								onChangeText={(txt) => { sendData.quantity = txt; }}
							/></View></InputRow>
					<InputRow text={'单位'}>
						<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => { }} activeOpacity={0.5} >
							<Text style={cStyles.text}>{'吨'}</Text>
						</TouchableOpacity>
					</InputRow>
					<InputRow text={'联系人'}>
						<View style={styles.inputRowRight}><Text style={cStyles.text}>{company.linkBy}</Text></View>
						{/* <TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => {
							curUserOptionType = 'contact';
							const { navigate } = this.props.navigation;
							navigate('ReferenceListPage', {
								goBackPage: 'RequirementAdd'
							});
						}} activeOpacity={0.5} >
							<Text style={cStyles.text}>{contact}</Text>
							<Image source={arrowPic} style={styles.arrowPic} />
						</TouchableOpacity> */}
					</InputRow>
					{/*<InputRow text={'联系电话'}><View style={styles.inputRowRight}>
						<View style={styles.inputRowRight}>
							<TextInput
								ref="linkPhoneInput"
								style={cStyles.textInput}
								underlineColorAndroid='transparent'
								placeholder={"请输入"}
								placeholderTextColor="#999"
								maxLength={30}
								editable={true}
								keyboardType="numeric"
								defaultValue={linkPhone}
								onChangeText={(txt) => {
									if (!/^[0-9]*$/.test(txt)) {
										this.refs.linkPhoneInput.clear();
										return;
									}
									sendData.linkTel = txt;
								}}
							/></View>
							</View></InputRow>*/}
					<InputRow text={'联系电话'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{company.linkPhone}</Text>
						</View>
					</InputRow>
					<InputRow text={'业务员'}>
						<View style={styles.inputRowRight}>
							<Text style={cStyles.text}>{reference}</Text>
						</View>
					</InputRow>
				</View>
			);
		}
	}
	/**
	 * 点击底部按钮
	 */
	async _didPressLargeBtn () {

		const { quantity } = sendData;
		if (ValidateDataUtil.isEmpty(quantity)) {
			//Alert.alert('请填写数量');
			ToastUtil.showWarning('请填写数量');
			this.refs.quantityInput.focus();
			return;
		}
		if ('LONG' === this.state.demandType) {
			if (quantity > this.state.company.quantity) {
				ToastUtil.showWarning('计划数量大于长约执行量' + this.state.company.quantity);
				this.refs.quantityInput.focus();
				return;
			}
		}
		var date = new Date;
		var month = date.getMonth() + 2;
		month = month > 12 ? 1 : month;
		const { demandType, deliveryMethod, logisticalList } = this.state;
		sendData.demandType = demandType;
		sendData.deliveryMethod = deliveryMethod;
		sendData.month = month;
		//for 物流信息
		let quantityCount = 0;//物流合计量
		const demandLogisticsVOS = logisticalList.map((logistical) => {
			console.log('logistical:', logistical);
			const { address, deliveryBeginDate, deliveryEndDate, quantity, addressStr } = logistical;
			quantityCount += (quantity || 0) * 1;
			return {
				address: address + addressStr,
				quantity,
				deliveryBeginDate: this._getDateStrEn(deliveryBeginDate) + ' ' + this._getTimeStr(deliveryBeginDate),
				deliveryEndDate: this._getDateStrEn(deliveryEndDate) + ' ' + this._getTimeStr(deliveryEndDate),
			}
		});
		if (quantity < quantityCount) {
			ToastUtil.showWarning('合计物流数量量必须小于计划数量');
			return;
		}
		console.log('客户需求计划:', sendData);
		this.setState({
			modalVisible: true
		})
		const responseData = await HTTP.POST(API_GENERATE(API.DAMAND_APPLY), { demandInfoVO: sendData, demandLogisticsVOS }, {
			rejectError: false,
			handleError: true,
			catchError: true,
		});
		if (responseData.error && responseData.error.msg) {
			const lastMsg = (responseData.error.msg.indexOf('稍后再试') == -1) ? null : '请您稍后再试';
			ToastUtil.showError(responseData.error.msg + lastMsg);
			return;
		} else {
			this.setState({
				modalVisible: false
			})

			ToastUtil.showSuccess('添加成功');
			this.timer = setTimeout(() => {
				this._goBack();
			}, 800)
		}
	}

	// 返回上一个页面
	_goBack = () => {
		DeviceEventEmitter.emit('requirementListener');
		const { navigate } = this.props.navigation;
		navigate('RequirementPlanPage', {
		});
	}

	_getLogisticalViews () {
		const { logisticalList } = this.state;

		return (
			logisticalList.map((logistical, index) => {
				const { quantity, address, deliveryBeginDate, deliveryEndDate, addressStr } = logistical;
				logistical.index = (index + 1);
				return (
					<TouchableOpacity key={index} style={styles.logisticalCell} activeOpacity={0.5} onPress={() => {
						const { navigate } = this.props.navigation;
						navigate('LogisticalPage', {
							logistical
						});
					}}>
						<View style={styles.logisticalRow}><Text style={cStyles.text14}>{`数量：${quantity} 吨`}</Text>
							<View style={styles.logisticalRight}>
								<TouchableOpacity style={{ alignSelf: 'flex-end' }} activeOpacity={0.5} onPress={this._delLogistical.bind(this, index)}>
									<Text style={styles.delText}>删除</Text>
								</TouchableOpacity>
							</View>
						</View>
						<View style={[styles.logisticalRow, { marginTop: 8 * scale, marginBottom: 8 * scale }]}><Text style={cStyles.text14}>{`提货时间：${this._getDateStr(deliveryBeginDate)}-${this._getDateStr(deliveryEndDate)}`}</Text></View>
						{/*<View style={styles.logisticalRow}><Text style={cStyles.text14}>出库地址：</Text>
						<View style={styles.logisticalRight}><Text style={cStyles.text14}>{address}{addressStr}</Text></View></View>*/}
					</TouchableOpacity>
				)
			})
		)
	}

	_delLogistical (index) {
		const { logisticalList } = this.state;
		logisticalList.splice((index - 1), 1);
		if (logisticalList.length === 0) {
			listNull = true;
			ifNull = true;
			this.props.navigation.state.params.logistical = false;
		}
		this.setState({
			logisticalList
		});
	}

	_getDateStr (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "年" + (m < 10 ? "0" + m : m) + "月" + (d < 10 ? "0" + d : d) + "日";
			return dateStr;
		} else {
			return '';
		}
	}

	_getDateStrEn (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
			return dateStr;
		} else {
			return '';
		}
	}

	_getTimeStr (currDate) {
		var h = currDate.getHours(),
			m = currDate.getMinutes(),
			s = currDate.getSeconds();
		var timeStr = "";
		timeStr += (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
		return timeStr;
	}
}

const styles = StyleSheet.create({
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
		position: 'absolute',
		left: 140 * scale,
		top: 150 * scale,
	},
	logisticalCell: {
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		position: 'relative',
	},
	logisticalRow: {
		flexDirection: 'row',
	},
	logisticalRight: {
		flex: 1,
		flexWrap: 'wrap',
	},
	delText: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
	},
	wuliuBtnCell: {
		width: 375 * scale,
		height: 77 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	wuliuBtn: {
		width: 351 * scale,
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		borderStyle: 'dashed',
		borderColor: '#979797',
		borderWidth: 1 / PixelRatio.get(),
		backgroundColor: '#F6F6F6',
		borderRadius: 5,
	},
	wuliuBtnText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
	},
	remarkCell: {
		paddingTop: 20 * scale,
		paddingBottom: 20 * scale,
	},
	remarkTextInput: {
		marginTop: 13 * scale,
		width: '100%',
		height: 80 * scale,
		backgroundColor: '#F9F9F9',
		borderRadius: 2,
		paddingTop: 5 * scale,
		paddingBottom: 3 * scale,
		paddingLeft: 5 * scale,
		paddingRight: 3 * scale,
		fontSize: 13 * scale,
		textAlignVertical: 'top',
	},
	arrowPic: {
		width: 6 * scale,
		height: 11 * scale,
	},
	inputRowRight: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
	},
	scrollView: {
		flex: 1,
		backgroundColor: '#fff',
	},
	container: {
		flex: 1,
		alignItems: 'center',
	},
	wrap: {
		width: 345 * scale,
	}, modalBg: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .6)',
		justifyContent: 'center',
		alignItems: 'center',
	},
})
